<template>
  <div>
    <div class='tinymce'>
        <editor id='myTinymce' v-model='textContent' :init='init'></editor>
        <Upload
            :uploadType="richTextImg"
            multiple
            ref="imageUpload"
            :action="uploadUrl"
            :on-success="insertImage"
            style="display:none"
            :headers="headers"
        ></Upload>
    </div>
  </div>
</template>

<script>
import { getToken, getCompanyId, getUserId } from "@/libs/util";
import { getImgUrl, getUploadUrl } from "@/api/server-url";
import upload from "_c/upload/upload.vue";
import tinymce from 'tinymce/tinymce'
import 'tinymce/themes/silver/theme'
import Editor from '@tinymce/tinymce-vue'
import 'tinymce/plugins/image'
import 'tinymce/plugins/link'
import 'tinymce/plugins/code'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/contextmenu'
import 'tinymce/plugins/wordcount'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'


export default {
  props:{
    text: {
      type:String,
      default:''
    },
    img:{
      type:String,
      default:''
    }
  },
  data() {
    return {
      headers: {
        yjyToken: getToken(),
        yjyCompanyId: getCompanyId(),
        yjyUserId: getUserId()
      },
      uploadUrl: "",
      textContent: this.text,
      richTextImg: this.img,
      init: {
        language_url: `/tinymce/skins/zh_CN.js`,
        selector: "#myTinymce",
        language: 'zh_CN',
        skin_url: '/tinymce/skins/ui/oxide',
        height: 300,
        plugins: 'link lists image code table colorpicker textcolor wordcount contextmenu',// 不显示插入图片按钮
        toolbar:[
          'bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify',
          'bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat imageUpload '],
        setup: (editor) => {
            editor.ui.registry.addButton('imageUpload', {
                tooltip: '插入图片',
                icon: 'image',
                onAction: () => {
                    let upload = this.$refs.imageUpload
                    upload.handleClick()
                }
            })
        },
        branding: false
      },
    }
  },
  methods: {
    // 插入图片至编辑器
      insertImage(res, file) {
          let src = getImgUrl(res.data.name); // 图片存储地址
          tinymce.execCommand("mceInsertContent", false, `<img src=${src}>`);
      },
  },
  activated() {
  },
  mounted() {
    tinymce.init({});
    this.uploadUrl = getUploadUrl(this.richTextImg);
  },
  watch:{
    textContent: function(val1, val2) {
        this.$emit('getRichText',val1);
    },
    text: function(val1) {
      this.textContent = val1;
    },
    img: function(val1) {
      this.richTextImg = val1;
    }
  },
  components: {
    Editor
  }
}
</script>

<style scoped lang='less'>

</style>